const UserDB = require("../../services/user/UserDB.js");
const crypto = require("crypto");
const jwt = require("../../jwt/jwt.js");
const multipart_file = require("../../utils/file-upload.js");
const fs = require("fs");

const fileexist = require("../../utils/fileExist.js");
const writeFile = require("../../utils/writeFile.js");

const PORT = 8888;
const HOST = "http://localhost";
const HOSTNAME = `${HOST}:${PORT}`;
const dir = require("../../CONST.js");

const UserController = {
  async login(req, res) {
    try {
      if (req.body.username === "" || req.body.md5pasw === "") {
        res.send({
          code: -1,
          message: "用户名或密码不能为空",
        });
        return;
      }

      /* 
        注意这个 const salt = "xiaoyan_my_salt"; //加盐加密的值
                   var md5 = crypto.createHash("md5");
                   代码不能提取，在添加用户部分再次写一次即可，写在外面退出登录再次登录会出现错误，不会执行二次加密
                   暂时找不到原因
      */
      const salt = "xiaoyan_my_salt"; //加盐加密的值
      var md5 = crypto.createHash("md5");
      // md5pasw是前端加密过的密码数据
      const md5pswsolt = md5.update(req.body.md5pasw + salt).digest("hex"); //二次加密

      // 如果登录查询用户信息可以查到，那么就存在数据，返回数组中必定存在一个元素
      let loginDBRes = await UserDB.login({
        md5pswsolt,
        username: req.body.username,
      });

      if (loginDBRes.length === 0) {
        // 不存在用户数据
        res.send({
          code: -1,
          message: "不存在用户！",
        });
        return;
      }

      // 存在用户则创建token和用户信息一起返回
      let token = jwt.sign({
        username: loginDBRes[0].username,
        md5pswsolt: loginDBRes[0].md5pswsolt,
      });
      res.send({
        code: 200,
        message: "登录成功！",
        token,
        username: loginDBRes[0].username,
        id: loginDBRes[0]._id,
      });
    } catch (error) {
      res.send({
        code: -1,
        message: "不存在用户！",
      });
    }
  },
  async getUserInfo(req, res) {
    let user = req.$TOKEN;
    try {
      let userInfo = await UserDB.login(user);
      if (userInfo.length === 0) {
        throw "获取用户信息失败!";
      }
      res.send({
        code: 200,
        message: "获取用户信息成功!",
        data: userInfo[0],
      });
    } catch (error) {
      res.send({
        code: -1,
        message: error,
      });
    }
  },
  async getUserMenu(req, res) {
    try {
      let data = await UserDB.getUserMenu({
        _id: req.query._id,
        role: +req.query.role,
      });
      res.send({
        code: 200,
        message: "ok",
        data: data,
      });
    } catch (error) {}
  },
  async getUserList(req, res) {
    try {
      let result = await UserDB.getUserList(req.query);
      let count = await UserDB.getUserListCount();

      res.send({
        code: 200,
        message: "查询成功",
        data: result,
        totalCount: count,
      });
    } catch (error) {
      res.send({
        code: -1,
        message: "查询用户列表失败",
      });
    }
  },
  async deleteUserListItem(req, res) {
    try {
      if (req.params.id === +"6513f8d9d4545fdfe32e6fc0") {
        res.send({
          code: -1,
          message: "不能删除该用户！",
        });
        return;
      }
      let result = await UserDB.deleteUserListItem(req.params.id);
      if (result.deletedCount === 1) {
        res.send({
          code: 200,
          message: "删除成功",
        });
      } else {
        res.send({
          code: -1,
          message: "删除失败",
        });
      }
    } catch (error) {}
  },
  async addUserList(req, res) {
    try {
      const salt = "xiaoyan_my_salt"; //加盐加密的值
      var md5 = crypto.createHash("md5");
      // 添加用户中需要处理默认密码行为，像性别和年龄都设置默认值，设计在个人中心和修改密码一起
      // 保存原始密码和二次加密密码
      var md5pswsolt = md5.update(req.body.md5pasw + salt).digest("hex"); //二次加密
      delete req.body.md5pasw; //不需要md5加密
      // 默认数据
      let initState = {
        age: 0,
        gender: 0,
        avatar: "",
        video: "",
        createtime: new Date(), //这些时间可以使用前端创建的时间传递，这里直接这里处理了
        updatetime: new Date(),
      };
      req.body = { ...req.body, md5pswsolt, ...initState };
      // 可以在将数据操作数据库的时候进行校验数据
      let result = await UserDB.addUserList(req.body); //将添加成功的数据返回

      if (result) {
        res.send({
          code: 200,
          message: "添加成功",
        });
      } else {
        throw "添加失败";
      }
    } catch (error) {
      res.send({
        code: -1,
        message: error,
      });
    }
  },
  async updateUserInfo(req, res) {
    try {
      // 处理用户密码加密
      if (req.body.md5pasw) {
        // 一个是用户列表界面修改数据，无密码加密项，一个是头像修改密码项会传递
        const salt = "xiaoyan_my_salt";
        var md5 = crypto.createHash("md5");
        var md5pswsolt = md5.update(req.body.md5pasw + salt).digest("hex");
        delete req.body.md5pasw;
        req.body = { ...req.body, md5pswsolt };
      }

      let result = await UserDB.updateUserInfo(req.params.id, req.body);
      if (result) {
        res.send({
          code: 200,
          message: "更新用户信息成功",
          result,
        });
      } else {
        throw "更新用户信息失败";
      }
    } catch (error) {
      res.send({
        code: -1,
        message: error,
      });
    }
  },
  async uploadFile(req, res) {
    try {
      let { files, fileds } = await multipart_file(req);
      let file = (files.file && files.file[0]) || {};
      let filename = (fileds.filename && fileds.filename[0]) || "";
      let path = `${dir}/upload/${filename}`;
      let isExist = false; //默认不存在

      isExist = await fileexist(path); //校验文件是否存在
      // 这里采用前端生成hash文件名返回给后端处理保存文件
      if (isExist) {
        //校验该地址是否存在
        res.send({
          code: 200,
          message: "文件上传成功或已存在",
          filePath: `${HOSTNAME}/upload/${dir.split("server")[1]}/${filename}`,
        });
      } else {
        // 创建文件
        writeFile(res, path, file, filename, true);
      }
    } catch (error) {}
  },
  async deleteAvatarFile(req, res) {
    try {
      // 删除用户头像
      // 删除对应数据库的数据
      let result = await UserDB.updateUserInfo(req.body._id, { avatar: "" });
      if (result) {
        // 删除本地文件
        fs.unlink(`${dir}\\upload\\${req.body.avatar}`, (err) => {
          if (err) {
            console.log("删除失败", req.body.avatar);
          }
        });
        res.send({
          code: 200,
          message: "删除头像成功",
          result,
        });
      } else {
        throw "删除头像失败";
      }
    } catch (error) {
      res.send({
        code: -1,
        message: error,
      });
    }
  },
  // 富文本图片上传处理
  async wordfile(req, res) {
    try {
      let { files } = await multipart_file(req, true); //自动上传，由插件自动生成文件名
      let file = (files.file && files.file[0]) || {};
      pathFile = file.path.split("server");

      let imgurl = pathFile[1].replace(/\\/g, "/");

      res.send({
        errno: 0,
        data: {
          url: HOSTNAME + `${imgurl}`, // 图片 src ，必须
        },
      });
    } catch (error) {}
  },
};

module.exports = UserController;
